package com.qjquestion.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qjquestion.exceptions.BusinessException;
import com.qjquestion.service.WeiXinApiService;
import com.qjquestion.util.UrlUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@Service
public class WeiXinApiServiceImpl implements WeiXinApiService {

    //获取openid的访问路径地址
    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Value("${weChat.AppID}")
    private String AppID;

    @Value("${weChat.AppSecret}")
    private String AppSecret;

    @Override
    @Transactional
    public String getOpenid(String code) {
        // 封装请求参数
        // 创建一个Map对象用于存储请求参数
        Map<String, String> params = new HashMap<>();
        // 设置小程序的AppID
        params.put("appid", AppID);
        // 设置小程序的AppSecret
        params.put("secret", AppSecret);
        // 设置从前端接收到的临时登录凭证code
        params.put("js_code", code);
        // 设置授权类型，固定值为"authorization_code"
        params.put("grant_type", "authorization_code");

        String requestUrl = UrlUtils.urlJoin(URL, params);

        var restTemplate = new RestTemplate();
        String response = "";
        try{
            response =  restTemplate.getForObject(requestUrl, String.class);
        }catch (Exception e){
            throw new BusinessException("微信请求登录异常");
        }
        JSONObject objectJson = JSON.parseObject(response);

        String openid = objectJson.getString("openid");
        if(openid.isBlank()){
            throw new BusinessException("登录失败");
        }
        return openid;

    }
}
